'''
Created on Mar 28, 2013

@author: Gabriel
'''
import mc
import threading
import urllib

class EpisodeCountersView :
    _WINDOW = 14002
    _TABLE_HEADER = 401
    _TABLE_LIST = 402

    episodeMgr = None
    databaseMgr = None
    
    def __init__(self, episodeMgr, databaseMgr):
        self.episodeMgr = episodeMgr
        self.databaseMgr = databaseMgr
        self.updateHeader()
        self.refreshTable()        

    def reset(self):
        self.episodeMgr.reset()
        self.refreshTable()
        
    def updateHeader(self):
        headerRow = mc.ListItems()
        item = mc.ListItem()
        item.SetLabel('Series')
        headerRow.append(item)
        item.SetLabel('Series')
        headerRow.append(item)
        item.SetLabel('Series')
        headerRow.append(item)
        item.SetLabel('Series')
        headerRow.append(item)
        mc.GetWindow(self._WINDOW).GetList(self._TABLE_HEADER).SetItems(headerRow)
    
    def refreshTable(self):
        mc.ShowDialogWait()
        currentItemIndex = mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).GetFocusedItem()
        mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).SetItems(self.episodeMgr.getEpisodeCountersForDisplay())
        if currentItemIndex > len(mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).GetItems()) - 1:
            currentItemIndex = len(mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).GetItems()) - 1
        mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).SetFocusedItem(currentItemIndex)
        mc.HideDialogWait()

    def getFocusedItem(self) :
        currentItemIndex = mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).GetFocusedItem()
        return mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).GetItem(currentItemIndex)

    def updateFocusedItemCounter(self, newCounter):
        focusedItem = self.getFocusedItem()
        self.episodeMgr.setCurrentEpisode(focusedItem.GetLabel(), newCounter)
        self.refreshTable()

    def getEpisodesCountForDisplay(self, seriesName):
        rangeList = range(self.databaseMgr.getEpisodeCount(seriesName))
        return map(str, rangeList)
        

class ScheduleView :
    _WINDOW = 14001
    _TABLE_HEADER = 401
    _TABLE_LIST = 402

    scheduleMgr = None
    databaseMgr = None
    
    def __init__(self, scheduleMgr, databaseMgr):
        self.scheduleMgr = scheduleMgr
        self.databaseMgr = databaseMgr
        self.updateHeader()
        self.refreshTable()
        #self.databaseMgr.download('http://192.168.1.4:8088/Development/videosDatabase.json')
        
    def updateHeader(self):
        headerRow = mc.ListItems()
        item = mc.ListItem()
        item.SetLabel('Time')
        headerRow.append(item)
        item = mc.ListItem()
        item.SetLabel('Mon')
        headerRow.append(item)
        item = mc.ListItem()
        item.SetLabel('Tue')
        headerRow.append(item)
        item = mc.ListItem()
        item.SetLabel('Wed')
        headerRow.append(item)
        item = mc.ListItem()
        item.SetLabel('Thu')
        headerRow.append(item)
        item = mc.ListItem()
        item.SetLabel('Fri')
        headerRow.append(item)
        item = mc.ListItem()
        item.SetLabel('Sat')
        headerRow.append(item)
        item = mc.ListItem()
        item.SetLabel('Sun')
        headerRow.append(item)
        mc.GetWindow(self._WINDOW).GetList(self._TABLE_HEADER).SetItems(headerRow)

    def removeRow(self) :
        self.scheduleMgr.removeRow(self.getFocusedItem().GetProperty('time'))
        self.refreshTable()

    def addRow(self) :
        selectedTime = self.getFocusedItem().GetProperty('time')
        self.scheduleMgr.addNextRow(selectedTime)
        self.refreshTable()

    def downloadSchedule(self, url):
        mc.ShowDialogWait()
        print('Updating database')
        self.scheduleMgr.download(url)
        self.refreshTable()
        mc.HideDialogWait()


    def getFocusedItem(self) :
        currentItemIndex = mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).GetFocusedItem()
        return mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).GetItem(currentItemIndex)

    def refreshTable(self) :
        mc.ShowDialogWait()
        currentItemIndex = mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).GetFocusedItem()
        mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).SetItems(self.scheduleMgr.getScheduleForDisplay())
        if currentItemIndex > len(mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).GetItems()) - 1:
            currentItemIndex = len(mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).GetItems()) - 1
        mc.GetWindow(self._WINDOW).GetList(self._TABLE_LIST).SetFocusedItem(currentItemIndex)
        mc.HideDialogWait()

    def isCurrentEntryTime(self):
        currentItem = self.getFocusedItem()
        return currentItem.HasProperty('isTime')
        
    def updateCurrentEntry(self, newValue):
        currentItem = self.getFocusedItem()
        if currentItem.HasProperty('isTime'):
            timep = str(currentItem.GetProperty('time'))
            self.scheduleMgr.updateScheduleTimeEntry(newValue, timep)
        else :
            timep = str(currentItem.GetProperty('time'))
            day = str(currentItem.GetProperty('day'))
            self.scheduleMgr.updateScheduleEntry(newValue, timep, day)
        self.refreshTable()


    def getAvailableVideos(self):
        availableVideos = self.databaseMgr.getShowsForDisplay()
        availableVideos.insert(0, '<movie>')
        availableVideos.insert(0, '<show>')
        return availableVideos


#
# Controls the main window
#
class MainWindowView : 
    # UI elements
    _WINDOW = 14000
    _TIMER_LABEL = 23

    _WAIT_TIME = 10
    
    running = False
    player = None
    
    def __init__(self, scheduleMgr, databaseMgr, episodeMgr):
        self.player = _RelaxeePlayer(scheduleMgr, databaseMgr, episodeMgr)
        
    def run(self):
        print ('RUN')
        if not self.running :
            self.start()
            self.__show()

    def start(self):
        print ('START')
        self.running = True
        self.__resetCounter()
    
    def stop(self):
        print ('STOP')
        self.running = False

    def updateVideosDatabase(self, url):
        mc.ShowDialogWait()
        self.stop()
        print('Updating database')
        self.player.databaseMgr.download(url)
        mc.HideDialogWait()
    
    def __show(self):
        print('Starting iteration')
        if self.running :
            print('Loop is running')
            self.counter -= 1
            window = mc.GetWindow(self._WINDOW)
            labelControl = window.GetLabel(self._TIMER_LABEL)
            labelControl.SetLabel(str(self.counter))
            if self.counter == 0 :
                self.stop()
                self.player.playNext()
            else : 
                t = threading.Timer(1.0, self.__show)
                t.start()
        else :
            print('Loop is over')

    def __resetCounter(self):
        self.counter = self._WAIT_TIME


class _RelaxeePlayer(mc.Player):
    episodeMgr = None
    scheduleMgr = None
    databaseMgr = None

    def __init__(self, scheduleMgr, databaseMgr, episodeMgr):
        self.episodeMgr = episodeMgr
        self.scheduleMgr = scheduleMgr
        self.databaseMgr = databaseMgr
        mc.Player.__init__(self)

    def playNext(self):
        playNextEntry = str(self.scheduleMgr.getNextScheduleEntry())
        incrementEpisode = True
        
        # If the schedule specifies only a genre, then play a random video of the genre    
        if playNextEntry == '<movie>' : 
            playNextPath = str(self.databaseMgr.getRandomMoviePath())
        elif playNextEntry == '<show>' :
            playNextPath = str(self.databaseMgr.getRandomEpisodePath())
            incrementEpisode = False
        else :
            currentEpisode = self.episodeMgr.getCurrentEpisode(playNextEntry)
            playNextPath = str(self.databaseMgr.getEpisodePath(playNextEntry, currentEpisode))

        print('Next program: '+ playNextEntry)
        print('File: '+ playNextPath)

        playNextItem = mc.ListItem()
        if 'http://' in playNextPath:
            print('Web content')
            playNextItem = mc.ListItem(mc.ListItem.MEDIA_VIDEO_EPISODE)
            playNextItem.SetContentType('text/html')
            encodedPath = urllib.urlencode({'url':playNextPath})
            playNextItem.SetPath('http://192.168.1.4:8088/Development/test.html?%s' % str(encodedPath))
        else:            
            playNextItem.SetPath(playNextPath)
        self.Play(playNextItem)
    
        if incrementEpisode :
            # Increment the episode count
            self.episodeMgr.incrementCurrentEpisode(playNextEntry, self.databaseMgr.getEpisodeCount(playNextEntry))

